package com.example.mytrainstation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class NearFarm extends ListActivity implements LocationListener {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d("mydebug", "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nearfarm);

		this.getListView().setEmptyView(findViewById(R.id.empty));
		//setAdapter();
	
		LocationManager status = (LocationManager) (this.getSystemService(LOCATION_SERVICE));
		if (status.isProviderEnabled(LocationManager.GPS_PROVIDER) || (status.isProviderEnabled(LocationManager.NETWORK_PROVIDER))){
			updateStat();
		}else{
			startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
		}
		
		//改成放在後面
		setAdapter();
	}
	
	private LocationManager mgr;
	private String best;
	private DB mDb;
	private Cursor mFarmsCursor;
	private Location location;
	
	private String[] farm_array = {
			"南澳自然田",
			"雲林二崙地瓜大哥",
			"台北楊儒門大哥"
	};
	
	private double[][] location_array = {
			{24.463757,121.800216},
			{23.816649,120.410532},
			{25.040563,121.554086}
	};

	
	private void setAdapter(){
		Log.d("mydebug", "getin setAdapter");
		mDb = new DB(this);
		mDb.open();
		
		fillData();
	}
	
	private void fillData(){
		
		mFarmsCursor = mDb.getAll();
		//Function: StartManagingCursor
		//也請Activity幫忙管理Cursor。This is, when the activity is stopped it will automatically call deactivate() on the given Cursor, 
		//and when it is later restarted it will call requery() for you.
		this.startManagingCursor(mFarmsCursor);
		
		//Farms排序~~~~~~~~~~
		//ArrayList<SortEntry> list = SortCursorByDistance(mFarmsCursor, location);  
		ArrayList<String> farmList = SortCursorByDistance(mFarmsCursor, location); 
		
		//使用cursor作為adapter
		//--------------------------------------------------------------------
		//Create an array to specify the fields we want to display in the list 
		//(下次測看看多列幾個fields)
		String[] from = new String[]{DB.KEY_NAME};
		
		//an array of the fields we want to bind those fields to
		//(查一下，看是不是也要多加fields)
		int[] to = new int[]{ android.R.id.text1};
		
		
		/*ListAdapter adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1,
				mFarmsCursor,
				from, 
				to);*/
		//--------------------------------------------------------------------
		
		ListAdapter adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1,
				farmList);
		
		this.setListAdapter(adapter);
	}
			
	private void updateStat(){
		
		Log.d("mydebug", "getin updateStat");
		
		mgr = (LocationManager) this.getSystemService(LOCATION_SERVICE);
		
		//選擇比較好的定位
		Criteria criteria = new Criteria();
		best = mgr.getBestProvider(criteria, true);
		Log.d("mydebug", best);
		//測試用
		best = "gps";
		location = mgr.getLastKnownLocation(best);
		//Location location = mgr.getLastKnownLocation(best);
		
		if (location != null){
			
			StringBuffer msg = new StringBuffer();
			msg.append("Latitude: ");
			msg.append(Double.toString(location.getLatitude()));
			msg.append(", Longitude: ");
			msg.append(Double.toString(location.getLongitude()));
			Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
			
		}else{	
			Toast.makeText(this, "No Location found", Toast.LENGTH_LONG).show();
		}
		
	}
	
	//以下為LocationListener的method
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		Log.d("mydebug", "getin onLocationChanged");
		Toast.makeText(this, "getin onLocationChanged", Toast.LENGTH_LONG).show();
		Toast.makeText(this, Double.toString(location.getLatitude()), Toast.LENGTH_LONG).show();
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}
	
	//Activity的Method
	@Override
	protected void onResume(){
		Log.d("mydebug", "onResume");
		super.onResume();
		mgr.requestLocationUpdates(best, 60000, 1, this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.d("mydebug", "onPause");
		super.onPause();
		mgr.removeUpdates(this);
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		Log.d("mydebug", "onRestart");
		super.onRestart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		Log.d("mydebug", "onStop");
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		Log.d("mydebug", "onDestroy");
		super.onDestroy();
	}
	
	// 計算距離及排序---------------------------------
	public float getDistance(double lat1, double lon1, double lat2, double lon2) {
		float[] results= new float[1];
		Location.distanceBetween(lat1, lon1, lat2, lon2, results);
		return results[0];
    }
	
	public class SortEntry {
		public float key; //計算出來的距離
		public int order;
		public String name;
		
		SortEntry(float key, int order, String name){
			this.key = key;
			this.order = order;
			this.name = name;
		}
		
	}
	
	//因為不知道要怎麼傳送SortEntry，暫時用ArrayList<String>代替
	//public ArrayList<SortEntry> SortCursorByDistance(Cursor cursor, Location nowLocation){
	public ArrayList<String> SortCursorByDistance(Cursor cursor, Location nowLocation){
		
		ArrayList<SortEntry> list = new ArrayList<SortEntry>();
		
		int rows_num = cursor.getCount();	//取得資料表列數
 
		if(rows_num != 0) {
			cursor.moveToFirst();			//將指標移至第一筆資料
				
			//把經緯度取出，計算距離，放入ArrayList裡面
			for(int i=0; i<rows_num; i++) {
				
				String name = cursor.getString(1);
				Double lat = cursor.getDouble(2);	
				Double log = cursor.getDouble(3);
				float temp = getDistance(lat,log, nowLocation.getLatitude(), nowLocation.getLongitude());
				SortEntry entry = new SortEntry(temp, i, name);
				list.add(entry);

				cursor.moveToNext();		//將指標移至下一筆資料
			}
		}
		
		//用Collections.sort進行排序
		Comparator<SortEntry> comparator = new Comparator<SortEntry>(){
		
			public int compare(SortEntry s1, SortEntry s2) {
				//compare
				if(s1.key > s2.key)
					return 1;
				else if (s1.key < s2.key)
					return -1;
				else 
					return 0;
			}
		};
		
		Collections.sort(list, comparator);
		
		//因不知如何直接使用list放到adapter，只好從排序好的list裡面，取出農場的名稱，放入單純的String的farmList裡
		ArrayList<String> farmList = new ArrayList<String>(); 
		for (int i=0; i<list.size(); i++){			
			farmList.add(list.get(i).name);
			Log.d("printf", Float.toString(list.get(i).key));
			Log.d("printf", Float.toString(list.get(i).order));
			Log.d("printf", farmList.get(i));
		}		

		return farmList;
		//return list;  //一個排序好的list<SortEntry>
	}
	
		
	//-------------------------------------------
	
	
}
